package com.wrupple.muba.catalogs.client.view.impl;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.wrupple.muba.catalogs.client.activity.process.task.CatalogInteractionState.Mode;
import com.wrupple.muba.catalogs.client.view.EditView;
import com.wrupple.muba.catalogs.client.widgets.editors.CatalogEditor;
import com.wrupple.muba.common.shared.StateTransition;

public class EditViewWithPreview<T extends JavaScriptObject> extends AbstractEditView<T> implements EditView<T> {

	class EditorLink implements ValueChangeHandler<T>{

		private TakesValue<T> preview;

		public EditorLink(TakesValue<T> preview) {
			this.preview=preview;
		}

		@Override
		public void onValueChange(ValueChangeEvent<T> event) {
			T value = event.getValue();
			preview.setValue(value);
		}
		
	}
	
	protected LayoutPanel previewContainer;
	private IsWidget preview;
	
	public EditViewWithPreview(CatalogEditor<T> editor,TakesValue<T> preview) {
		super(editor);
		IsWidget previewWidget = (IsWidget) preview;
		editor.addValueChangeHandler(new EditorLink(preview));
		previewContainer = new LayoutPanel();
		previewContainer.add(previewWidget);
		previewContainer.add(editor);
		if (LocaleInfo.getCurrentLocale().isRTL()) {
			//right to reft
			previewContainer.setWidgetLeftWidth(previewWidget, 0, Unit.PX, 50, Unit.PCT);
			previewContainer.setWidgetRightWidth(editor, 0, Unit.PX, 50, Unit.PCT);
		} else {
			previewContainer.setWidgetLeftWidth(editor, 0, Unit.PX, 50, Unit.PCT);
			previewContainer.setWidgetRightWidth(previewWidget, 0, Unit.PX, 50, Unit.PCT);
		}
		this.preview=previewWidget;
		main.getContentContainer().setWidget(previewContainer);
	}
	
	@Override
	public void start(T entry, StateTransition<T> onDone, EventBus bus) {
		if(editor.getMode()==Mode.READ){
			previewContainer.remove(editor);
			previewContainer.setWidgetLeftRight(preview, 0, Unit.PX,0, Unit.PX);
		}
		super.start(entry, onDone, bus);
	}
	
}